import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { auth } from '@/auth';

// 检查用户是否有权限访问项目
async function checkProjectAccess(userId: string, projectId: string) {
  const projectUser = await prisma.projectUser.findUnique({
    where: {
      userId_projectId: {
        userId,
        projectId,
      },
    },
  });
  
  return !!projectUser;
}

// 获取任务列表或单个任务
export async function GET(request: NextRequest) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, message: '未授权' },
        { status: 401 }
      );
    }

    // 获取查询参数
    const searchParams = request.nextUrl.searchParams;
    const taskId = searchParams.get('id');
    const projectId = searchParams.get('projectId');
    const userId = session.user.id;

    // 如果提供了任务ID，返回单个任务
    if (taskId) {
      const task = await prisma.task.findUnique({
        where: { id: taskId },
        include: {
          assignee: {
            select: {
              id: true,
              name: true,
              image: true
            }
          },
          project: {
            select: {
              id: true,
              name: true
            }
          }
        }
      });
      
      if (!task) {
        return NextResponse.json(
          { success: false, message: '任务不存在' },
          { status: 404 }
        );
      }
      
      // 检查用户是否有权限访问该任务所属的项目
      const hasAccess = await checkProjectAccess(userId, task.projectId);
      
      if (!hasAccess) {
        return NextResponse.json(
          { success: false, message: '没有权限访问该任务' },
          { status: 403 }
        );
      }
      
      // 处理标签信息
      let tags = [];
      try {
        // 尝试从Prisma模型中获取标签信息
        if (task.data && typeof task.data === 'object') {
          const taskData = task.data as any;
          if (Array.isArray(taskData.tags)) {
            tags = taskData.tags;
          }
        }
      } catch (err) {
        console.error('解析标签数据时出错:', err);
      }

      // 返回任务信息，包含标签
      return NextResponse.json({ 
        success: true, 
        data: {
          ...task,
          tags
        } 
      });
    }
    
    // 如果提供了项目ID，返回该项目的所有任务
    if (projectId) {
      // 检查用户是否有权限访问该项目
      const hasAccess = await checkProjectAccess(userId, projectId);
      
      if (!hasAccess) {
        return NextResponse.json(
          { success: false, message: '没有权限访问该项目的任务' },
          { status: 403 }
        );
      }
      
      const tasks = await prisma.task.findMany({
        where: { projectId },
        include: {
          assignee: {
            select: {
              id: true,
              name: true,
              image: true
            }
          }
        },
        orderBy: { updatedAt: 'desc' }
      });
      
      return NextResponse.json({ success: true, data: tasks });
    }
    
    // 否则返回用户可访问的所有任务
    const userProjects = await prisma.projectUser.findMany({
      where: { userId },
      select: { projectId: true }
    });
    
    const projectIds = userProjects.map(pu => pu.projectId);
    
    const tasks = await prisma.task.findMany({
      where: {
        projectId: { in: projectIds }
      },
      include: {
        assignee: {
          select: {
            id: true,
            name: true,
            image: true
          }
        },
        project: {
          select: {
            id: true,
            name: true
          }
        }
      },
      orderBy: { updatedAt: 'desc' }
    });
    
    return NextResponse.json({ success: true, data: tasks });
  } catch (error: any) {
    console.error('获取任务失败:', error);
    return NextResponse.json(
      { success: false, message: '获取任务失败', error: error.message },
      { status: 500 }
    );
  }
}

// 创建新任务
export async function POST(request: NextRequest) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    const body = await request.json();
    const userId = session.user.id;
    
    // 增强验证
    const validationErrors = [];
    if (!body.title || body.title.trim() === '') {
      validationErrors.push('任务标题不能为空');
    }
    
    if (!body.projectId) {
      validationErrors.push('项目ID不能为空');
    }
    
    if (validationErrors.length > 0) {
      return NextResponse.json(
        { 
          success: false, 
          message: '请填写所有必填字段', 
          errors: validationErrors 
        },
        { status: 400 }
      );
    }
    
    // 验证项目是否存在
    const project = await prisma.project.findUnique({
      where: { id: body.projectId }
    });
    
    if (!project) {
      return NextResponse.json(
        { success: false, message: '指定的项目不存在' },
        { status: 404 }
      );
    }
    
    // 验证用户是否有权限在该项目中创建任务
    const hasAccess = await checkProjectAccess(userId, body.projectId);
    
    if (!hasAccess) {
      return NextResponse.json(
        { success: false, message: '没有权限在此项目中创建任务' },
        { status: 403 }
      );
    }
    
    // 验证被分配的用户是否存在（如果有）
    if (body.assigneeId) {
      const assignee = await prisma.user.findUnique({
        where: { id: body.assigneeId }
      });
      
      if (!assignee) {
        return NextResponse.json(
          { success: false, message: '指定的被分配用户不存在' },
          { status: 404 }
        );
      }
      
      // 验证被分配的用户是否有权限访问该项目
      const assigneeAccess = await checkProjectAccess(body.assigneeId, body.projectId);
      
      if (!assigneeAccess) {
        return NextResponse.json(
          { success: false, message: '被分配用户没有访问该项目的权限' },
          { status: 403 }
        );
      }
    }
    
    // 创建任务
    const task = await prisma.$transaction(async (tx) => {
      try {
        // 状态规范化处理
        let normalizedStatus = 'TODO';
        if (body.status) {
          // 将状态统一转为大写
          const status = body.status.toUpperCase();
          // 验证状态是否为有效值
          if (['TODO', 'IN_PROGRESS', 'REVIEW', 'DONE'].includes(status)) {
            normalizedStatus = status;
          } else {
            console.warn(`任务状态值 "${body.status}" 无效，使用默认值 "TODO"`);
          }
        }
        
        // 优先级规范化处理
        let normalizedPriority = 'MEDIUM';
        if (body.priority) {
          // 将优先级统一转为大写
          const priority = body.priority.toUpperCase();
          // 验证优先级是否为有效值
          if (['LOW', 'MEDIUM', 'HIGH', 'URGENT'].includes(priority)) {
            normalizedPriority = priority;
          } else {
            console.warn(`任务优先级值 "${body.priority}" 无效，使用默认值 "MEDIUM"`);
          }
        }
        
        // 处理标签和其他任务数据
        const taskData = {};
        if (Array.isArray(body.tags)) {
          taskData['tags'] = body.tags;
        }
        
        // 创建新任务
        const newTask = await tx.task.create({
          data: {
            title: body.title.trim(),
            description: body.description ? body.description.trim() : '',
            status: normalizedStatus,
            priority: normalizedPriority,
            projectId: body.projectId,
            assigneeId: body.assigneeId,
            dueDate: body.dueDate ? new Date(body.dueDate) : null,
            data: Object.keys(taskData).length > 0 ? taskData : undefined
          }
        });
        
        // 创建活动记录
        await tx.activity.create({
          data: {
            userId,
            type: 'task_created',
            entityId: newTask.id,
            data: {
              taskTitle: body.title,
              projectId: body.projectId
            }
          }
        });
        
        // 如果分配了用户且不是创建者本人，创建通知
        if (body.assigneeId && body.assigneeId !== userId) {
          await tx.notification.create({
            data: {
              type: 'TASK_ASSIGNED',
              title: '新任务分配',
              content: `您被分配了一个新任务: "${body.title}"`,
              recipients: {
                create: {
                  userId: body.assigneeId
                }
              }
            }
          });
        }
        
        return newTask;
      } catch (err) {
        console.error('事务中创建任务失败:', err);
        throw err;
      }
    });
    
    // 获取包含关联数据的完整任务
    const fullTask = await prisma.task.findUnique({
      where: { id: task.id },
      include: {
        assignee: {
          select: {
            id: true,
            name: true,
            image: true
          }
        },
        project: {
          select: {
            id: true,
            name: true
          }
        }
      }
    });
    
    return NextResponse.json(
      { success: true, message: '任务创建成功', data: fullTask },
      { status: 201 }
    );
  } catch (error: any) {
    console.error('创建任务失败:', error);
    
    // 提供更具体的错误信息
    let errorMessage = '创建任务失败';
    let statusCode = 500;
    
    if (error.code === 'P2002') {
      errorMessage = '任务创建失败：可能存在重复记录';
      statusCode = 409;
    } else if (error.code === 'P2003') {
      errorMessage = '任务创建失败：引用的外键约束失败';
      statusCode = 400;
    } else if (error.message) {
      errorMessage = error.message;
    }
    
    return NextResponse.json(
      { 
        success: false, 
        message: errorMessage, 
        error: process.env.NODE_ENV === 'development' ? error.toString() : undefined 
      },
      { status: statusCode }
    );
  }
}

// 更新任务
export async function PUT(request: NextRequest) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, message: '未授权' },
        { status: 401 }
      );
    }

    const searchParams = request.nextUrl.searchParams;
    const taskId = searchParams.get('id');
    const userId = session.user.id;
    
    if (!taskId) {
      return NextResponse.json(
        { success: false, message: '未提供任务ID' },
        { status: 400 }
      );
    }
    
    // 查找任务并检查是否存在
    const existingTask = await prisma.task.findUnique({
      where: { id: taskId }
    });
    
    if (!existingTask) {
      return NextResponse.json(
        { success: false, message: '任务不存在' },
        { status: 404 }
      );
    }
    
    // 检查用户是否有权限编辑该任务
    const hasAccess = await checkProjectAccess(userId, existingTask.projectId);
    
    if (!hasAccess) {
      return NextResponse.json(
        { success: false, message: '没有权限编辑该任务' },
        { status: 403 }
      );
    }
    
    const body = await request.json();
    
    // 准备更新数据
    const updateData: any = {};
    
    if (body.title !== undefined) updateData.title = body.title;
    if (body.description !== undefined) updateData.description = body.description;
    if (body.status !== undefined) updateData.status = body.status;
    if (body.priority !== undefined) updateData.priority = body.priority;
    if (body.assigneeId !== undefined) updateData.assigneeId = body.assigneeId || null;
    if (body.dueDate !== undefined) updateData.dueDate = body.dueDate ? new Date(body.dueDate) : null;
    
    // 执行更新
    const updatedTask = await prisma.$transaction(async (tx) => {
      // 如果分配的用户发生变化且新分配了用户，发送通知
      if (body.assigneeId !== undefined && 
          body.assigneeId !== existingTask.assigneeId && 
          body.assigneeId && 
          body.assigneeId !== userId) {
        // 创建通知
        await tx.notification.create({
          data: {
            type: 'TASK_ASSIGNED',
            title: '任务分配',
            content: `您被分配了任务: "${existingTask.title}"`,
            recipients: {
              create: {
                userId: body.assigneeId
              }
            }
          }
        });
      }
      
      // 更新任务
      const task = await tx.task.update({
        where: { id: taskId },
        data: updateData
      });
      
      // 记录活动
      await tx.activity.create({
        data: {
          userId,
          type: 'task_updated',
          entityId: taskId,
          data: {
            taskTitle: existingTask.title,
            projectId: existingTask.projectId,
            updates: Object.keys(updateData)
          }
        }
      });
      
      return task;
    });
    
    // 获取包含关联数据的完整任务
    const fullTask = await prisma.task.findUnique({
      where: { id: updatedTask.id },
      include: {
        assignee: {
          select: {
            id: true,
            name: true,
            image: true
          }
        },
        project: {
          select: {
            id: true,
            name: true
          }
        }
      }
    });
    
    return NextResponse.json({ 
      success: true, 
      message: '任务更新成功', 
      data: fullTask
    });
  } catch (error: any) {
    console.error('更新任务失败:', error);
    return NextResponse.json(
      { success: false, message: '更新任务失败', error: error.message },
      { status: 500 }
    );
  }
}

// 删除任务
export async function DELETE(request: NextRequest) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, message: '未授权' },
        { status: 401 }
      );
    }

    const searchParams = request.nextUrl.searchParams;
    const taskId = searchParams.get('id');
    const userId = session.user.id;
    
    if (!taskId) {
      return NextResponse.json(
        { success: false, message: '未提供任务ID' },
        { status: 400 }
      );
    }
    
    // 查找任务并检查是否存在
    const task = await prisma.task.findUnique({
      where: { id: taskId }
    });
    
    if (!task) {
      return NextResponse.json(
        { success: false, message: '任务不存在' },
        { status: 404 }
      );
    }
    
    // 检查用户是否有权限删除该任务（需要是项目成员）
    const projectUser = await prisma.projectUser.findUnique({
      where: {
        userId_projectId: {
          userId,
          projectId: task.projectId
        }
      }
    });
    
    if (!projectUser || !['OWNER', 'ADMIN'].includes(projectUser.role)) {
      return NextResponse.json(
        { success: false, message: '没有权限删除该任务' },
        { status: 403 }
      );
    }
    
    // 执行删除
    await prisma.$transaction(async (tx) => {
      // 删除任务相关的评论
      await tx.comment.deleteMany({
        where: { taskId }
      });
      
      // 删除任务
      await tx.task.delete({
        where: { id: taskId }
      });
      
      // 记录活动
      await tx.activity.create({
        data: {
          userId,
          type: 'task_deleted',
          entityId: task.projectId, // 使用项目ID作为实体ID，因为任务已被删除
          data: {
            taskTitle: task.title,
            projectId: task.projectId
          }
        }
      });
    });
    
    return NextResponse.json(
      { success: true, message: '任务删除成功' }
    );
  } catch (error: any) {
    console.error('删除任务失败:', error);
    return NextResponse.json(
      { success: false, message: '删除任务失败', error: error.message },
      { status: 500 }
    );
  }
}